package org.peoplesearch.vk.executor;


import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class VkAPiExecutor {

    List<CredentialExecutor> credentialExecutors = new LinkedList<CredentialExecutor>();

    public VkAPiExecutor(Collection<VKAuthCredential> credentials) {
        for (VKAuthCredential credential : credentials) {
            credentialExecutors.add(new CredentialExecutor(credential));
        }
    }

    public void addCommand(VkCommand command) {
        getCredentialExecutor().addTask(command);
    }


    public boolean terminate(int sec) {
        boolean rezult = true;
        for (CredentialExecutor credentialExecutor : credentialExecutors) {
            rezult = rezult && credentialExecutor.terminate(sec);
        }
        return rezult;
    }

    public int getTasksInQueue() {
        int tasks = 0;
        for (CredentialExecutor credentialExecutor : credentialExecutors) {
            tasks = tasks + credentialExecutor.getAverageTasksToBeExecuted();
        }
        return tasks;
    }

    public void waitForCompletion() {
        for (CredentialExecutor credentialExecutor : credentialExecutors) {
            credentialExecutor.waitForCompletion();
        }
    }

    private CredentialExecutor getCredentialExecutor() {
        CredentialExecutor rez = credentialExecutors.get(0);
        for (CredentialExecutor i : credentialExecutors) {
            if (rez.getAverageTasksToBeExecuted() > i.getAverageTasksToBeExecuted()) {
                rez = i;
            }
        }
        return rez;
    }


}
